package com.dkha.server.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dkha.common.enums.ApiUrlEnum;
import com.dkha.common.enums.YNEnums;
import com.dkha.common.exception.DkException;
import com.dkha.common.fileupload.MinioUtil;
import com.dkha.common.http.HttpUtil;
import com.dkha.common.modules.vo.ApiVO;
import com.dkha.common.modules.vo.dto.FaceLibraryVO;
import com.dkha.common.page.PageParam;
import com.dkha.common.redis.RedisUtils;
import com.dkha.common.systemcode.SystemCode;
import com.dkha.common.util.UtilValidate;
import com.dkha.server.mappers.ControlLibraryMidMapper;
import com.dkha.server.mappers.PortraitMapper;
import com.dkha.server.modules.entities.FaceLibrary;
import com.dkha.server.mappers.FaceLibraryMapper;
import com.dkha.server.modules.entities.Portrait;
import com.dkha.server.services.IFaceLibraryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 库表 服务实现类
 * </p>
 *
 * @author Spring
 * @since 2019-12-09
 */
@Service
public class FaceLibraryServiceImpl extends ServiceImpl<FaceLibraryMapper, FaceLibrary> implements IFaceLibraryService {
    /**库mapper*/
    @Resource
   private FaceLibraryMapper faceLibraryMapper;
    @Resource
    private ControlLibraryMidMapper controlLibraryMidMapper;
    @Resource
    private PortraitMapper portraitMapper;

    @Value("${api.server.prefix}")
    private String link;
    @Resource
    private HttpUtil httpUtil;
    @Autowired
    private Gson gson;
    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private RedisUtils redisUtils;
    @Value("${api.server.prefix}")
    private String apiRequestPrefix;
    @Value("${minio.bucketName}")
    private String bucketName;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FaceLibrary addLibrary(FaceLibrary faceLibrary) {
        try {
            if (faceLibraryMapper.getLibraryByFactoryName(faceLibrary.getFactoryName()) != null) {
                throw new DkException("库名称已存在");
            }
            FaceLibraryVO faceLibraryVO = new FaceLibraryVO();
            faceLibraryVO.setLibraryId(faceLibrary.getIdFactory().toString());
            faceLibraryVO.setName(faceLibrary.getFactoryName());
            ApiVO faceLibrary1 = (ApiVO) httpUtil.post(link + ApiUrlEnum.FACELIB_POSTURL.getUrl(), faceLibraryVO, ApiVO.class);
            if (! faceLibrary1.getCode().equals(200)) {
                throw new DkException("算法端新增库失败, " + faceLibrary1.getMessage());
            }
            int insert = faceLibraryMapper.insert(faceLibrary);
            if(insert<0){
                throw new DkException("MySQL新增库失败");
            }
            return faceLibrary;
        }catch (Exception e){
            throw new DkException("新增库失败"+e.getMessage());
        }
    }

    @Override
    public FaceLibrary deleteLibrary(Long  libraryId) {
        FaceLibrary faceLibrary = new FaceLibrary();
        faceLibrary.setIsValid(YNEnums.NO.code);
        faceLibrary.setIdFactory(libraryId);
        try {
            ApiVO faceLibrary1 = (ApiVO) httpUtil.delete(link + ApiUrlEnum.FACELIB_POSTURL.getUrl() + "/" + libraryId, ApiVO.class);
            if (! faceLibrary1.getCode().equals(200)) {
                throw new DkException("删除库失败, " + faceLibrary1.getMessage());
            }
        }catch (Exception e){
            throw new DkException(e.getMessage());
        }
        /**调用API*/
        Integer integer = controlLibraryMidMapper.selectByLibID(String.valueOf(libraryId), YNEnums.YES.code);
        if(integer<=0) {
            int count = faceLibraryMapper.deleteById(faceLibrary);
            /**删除对应的人像*/
            List<Portrait> portraits = portraitMapper.queryPortraitByFactory(libraryId);
            portraitMapper.deletePortrait(libraryId);
            if(UtilValidate.isNotEmpty(portraits)){
                for (Portrait p:portraits) {
                    /**删除文件服务器*/
                    try {
                        minioUtil.removeObject(bucketName,p.getUrl());
                    } catch (Exception e) {
                        log.error(e.getMessage());
                        //throw new DkException("文件服务器图片删除失败");
                    }
                }
            }
            if (count < 0) {
                throw new DkException("删除库失败");
            }
        }else{
            throw new DkException(SystemCode.DELETELIB_ERROR.code,"该库有关联的布控信息，不能删除！");
        }

        return faceLibrary;
    }

    @Override
    public FaceLibrary updateLibrary(FaceLibrary faceLibrary) {
        try {
        int count = faceLibraryMapper.updateById(faceLibrary);
            FaceLibraryVO faceLibraryVO = new FaceLibraryVO();
            faceLibraryVO.setName(faceLibrary.getFactoryName());
            faceLibraryVO.setLibraryId(String.valueOf(faceLibrary.getIdFactory()));
            ApiVO face = (ApiVO) httpUtil.put(link+ ApiUrlEnum.FACELIB_POSTURL.getUrl(),faceLibraryVO, ApiVO.class);
            if(!face.getMessage().equals("成功")) {
                throw new DkException("wy修改库失败");
            }
        }catch (Exception e){
            log.error(e.getMessage());
            throw new DkException("修改库失败");
        }
        return faceLibrary;
    }

    @Override
    public Page<FaceLibrary> queryLibrary(PageParam pageParam) {
        /**创建page对象*/
        Page<FaceLibrary> page = new Page<>(pageParam.getPageNo(), pageParam.getPageSize());
        /**设置模糊查询参数*/
        Map<String, String> paramsNote = pageParam.getNote();

        /**分页查询*/
        List<FaceLibrary> postList = faceLibraryMapper.getLibraryPage(page, paramsNote.get("factoryName"));
        if(UtilValidate.isNotEmpty(postList)){
            for (FaceLibrary p: postList) {
                Integer libraryCount = faceLibraryMapper.getLibraryCount(p.getIdFactory());
                if(libraryCount>0) {
                    p.setNumber(String.valueOf(libraryCount));
                }else{
                    p.setNumber("0");
                }
            }

        }
        page.setRecords(postList);
        return page;
    }

    @Override
    public List<FaceLibrary> findFaceLibraries() {
        QueryWrapper<FaceLibrary> queryWrapper = new QueryWrapper();
        queryWrapper.eq("is_valid", YNEnums.YES.code);
        queryWrapper.orderByDesc("create_time");
        return baseMapper.selectList(queryWrapper);
    }

}
